package com.entrogy.timing;

import com.entrogy.controller.StudentScoreController;
import com.entrogy.dao.StudentScoreMapper;
import com.entrogy.utils.RedissonManager;
import com.entrogy.utils.ScoreTableNameUtil;
import com.entrogy.utils.constants.Constants;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName CreateScoreTableTiming
 * @Description
 * @Author luoxingjiang
 * @Date 2019/7/4 0004 上午 9:50
 * @Version 1.0
 **/
@Component
public class CreateScoreTableTiming {


    private static final Logger logger = LoggerFactory.getLogger(CreateScoreTableTiming.class);

    @Autowired
    private StudentScoreMapper studentScoreMapper;
    @Autowired
    private RedissonManager redissonManager;

    //3.添加定时任务
    @Scheduled(cron = "0 01 0 1 * ?")//每月1号的0:01:00执行
    private void configureTasks() {
        RLock lock = redissonManager.getRedisson().getLock(Constants.STUDENT_SCORE_TASK_LOCK);
        boolean getLock = false;
        try {
            if (getLock = lock.tryLock(0, 5, TimeUnit.SECONDS)) {
                Date currentTime = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
                //根据日期生成表名
                String scoreTableName = ScoreTableNameUtil.createScoreTableName(dateFormat.format(currentTime));
                logger.info("执行定时任务创建成绩表: " + scoreTableName + "创建时间：" + LocalDateTime.now());
                studentScoreMapper.timingCreateScoreTable(scoreTableName);
            } else {
                logger.info("每月1号创建成绩表的时候锁没有获取到锁");
            }
            Thread.sleep(5000);//睡一会儿在关闭锁
        } catch (InterruptedException e) {
            logger.error("每月1号创建成绩表的时候获取锁异常",e);
        }finally {
            if (!getLock) {
                return;
            }
            lock.unlock();
            logger.info("每月1号创建成绩表的时候释放锁");
        }
    }
}
